今天用了sharedpreferences,在mvvm架構上要使用respository來當作model來傳遞資料
那sharedpreference如果不是寫在activity記得要把context傳進建構值
class Repository (context: Context){
private val sharedPreferences = context.getSharedPreferences("User", Context.MODE_PRIVATE)
private val editor = sharedPreferences.edit()
fun savedpreferences(account:String , password:String){
editor.putString("account",account).putString("password",password).commit()
}
fun getpreferences(): SharedPreferences? {
return sharedPreferences
}
fun clearpreference(){
editor.clear().commit()
}
}
然後是viewmodel
class MainViewModel(application: Application): AndroidViewModel(application) {
fun saveddata(account: String, password: String) {
Repository(getApplication()).savedpreferences(account,password)
}
fun getdata(){
val account = Repository(getApplication()).getpreferences()!!.getString("account","")
val password = Repository(getApplication()).getpreferences()!!.getString("password","")
Toast.makeText(getApplication(),account+password,Toast.LENGTH_SHORT).show()
}
fun cleardata(){
Repository(getApplication()).clearpreference()
}
}
還有一個在activity監聽的按鈕
viewModel.result.observe(this){
when(it){
is MainDialogResult.Ok ->{
mainViewModel.saveddata(it.account,it.password)
}
is MainDialogResult.Cancel ->{
Toast.makeText(this,"cancel",Toast.LENGTH_SHORT).show()
}
}
}
成果如下
clear之後